package com.aia.prm.web.ria.app.ui.lms;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;

import com.aia.prm.BeanFactory;
import com.aia.prm.domain.VOLms;
import com.aia.prm.domain.VOLmsExample;
import com.aia.prm.domain.VOLmsExample.Criteria;
import com.aia.prm.domain.VOPlan;
import com.aia.prm.persistence.dao.VOLmsDAO;
import com.aia.prm.persistence.dao.VOPlanDAO;
import com.aia.prm.service.DefaultService;
import com.aia.prm.service.MemoryLog;
import com.aia.prm.service.ServiceResult;
import com.aia.prm.web.ria.app.PrmApplication;
import com.aia.prm.web.ria.app.ui.AlertDialog;
import com.aia.prm.web.ria.app.ui.ConfirmDialog;
import com.cfh.util.Tools;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.util.BeanItem;
import com.vaadin.terminal.ExternalResource;
import com.vaadin.terminal.Sizeable;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Form;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.HorizontalSplitPanel;
import com.vaadin.ui.Label;
import com.vaadin.ui.Link;
import com.vaadin.ui.PopupView;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.VerticalSplitPanel;
import com.vaadin.ui.Window.Notification;

@SuppressWarnings("serial")
public class LmsView extends VerticalLayout implements Property.ValueChangeListener {
	private static final Logger logger = Logger.getLogger(LmsView.class);
	private PrmApplication app = null;
	VerticalSplitPanel vert = null;
	HorizontalSplitPanel horiz = null;
	VerticalLayout rightLayout = null;
	LmsList LmsList = null;
	Form form = null;
	LmsContainer LmsContainer = null;
	LmsForm LmsForm = null;
	private VOLmsDAO LmsDAO = null;
	List<VOLms> list = null;

	VerticalLayout topLayout = null;
	Button newButton = null;
	Button xmlButton = null;
	Button logButton = null;
	Button okButton = null;

	TextField startDate = new TextField();
	TextField endDate = new TextField();

	private ComboBox plansBox = null;
	private ComboBox statusBox = null;
	private ComboBox varifyBox = null;
	TextField refCodeField = new TextField();
	TextField nameField = new TextField();

	TextField mobileField = new TextField();
	DefaultService defaultService = null;

	Label logContent = new Label("发送日志", Label.CONTENT_XHTML);
	{
		logContent.setCaption("发送日志:");
	}
	PopupView logPopup = new PopupView("点击查看发送日志", logContent);

	CheckBox checkMobile = new CheckBox("是否校验手机号", true);
	{
		checkMobile.setDescription("每个手机号只能给LMS发送一次消息，取消勾选此项可以强制发消息");
	}

	CheckBox checkCallMe = new CheckBox("要求营销员联系", false);
	{
		checkCallMe.setDescription("向用户手机号码发送短信的次数已达到上限的时候，用户可以点击按钮让营销员联系用户，勾选此项可以查看这些用户记录");
	}
	
	ComboBox isComeFromMiniBox = null;

	Link downloadReportLink = null;

	public LmsView(PrmApplication aapp) {
		app = aapp;
		setLmsDAO((VOLmsDAO) BeanFactory.get().getBean("vOLmsDAO"));
		init();
		buildMainLayout();
		load();
	}

	private void init() {
		downloadReportLink = new Link("下载报表", new ExternalResource(app.getFullContextPath() + "/reportLms/"));
		{
			downloadReportLink.setTargetName("_blank");
			downloadReportLink.setTargetBorder(Link.TARGET_BORDER_NONE);
			downloadReportLink.setDescription("请选择合适的查询条件，下载过多的记录会可能会给系统造成压力");
			addComponent(downloadReportLink);
		}

		defaultService = (DefaultService) BeanFactory.get().getBean("defaultService");
		startDate.setInputPrompt("yyyymmdd");
		endDate.setInputPrompt("yyyymmdd");
		startDate.setValue(Tools.getToday());
		endDate.setValue(Tools.getToday());

		startDate.setWidth(80F, Sizeable.UNITS_PIXELS);
		endDate.setWidth(80F, Sizeable.UNITS_PIXELS);
		refCodeField.setWidth(40F, Sizeable.UNITS_PIXELS);

		nameField.setWidth(60F, Sizeable.UNITS_PIXELS);

		statusBox = new ComboBox();
		statusBox.addItem("仅显示发送失败记录");
		statusBox.addItem("仅显示发送成功记录");
		statusBox.addItem("显示所有");
		statusBox.setNullSelectionAllowed(false);
		statusBox.setValue("显示所有");

		varifyBox = new ComboBox();
		varifyBox.addItem("手机号已经校检过");
		varifyBox.addItem("手机号未校检过");
		varifyBox.addItem("显示所有");
		varifyBox.setNullSelectionAllowed(false);
		varifyBox.setValue("显示所有");
		
		
		isComeFromMiniBox = new ComboBox();
		isComeFromMiniBox.addItem("只显示来自迷你版");
		isComeFromMiniBox.addItem("只显示来自普通版");
		isComeFromMiniBox.addItem("来源:显示所有");
		isComeFromMiniBox.setNullSelectionAllowed(false);
		isComeFromMiniBox.setValue("来源:显示所有");

		plansBox = new ComboBox();
		VOPlanDAO vOPlanDAO = (VOPlanDAO) BeanFactory.get().getBean("vOPlanDAO");
		List list = vOPlanDAO.selectByExample(null);
		String firstItem = null;
		for (Object o : list) {
			VOPlan p = (VOPlan) o;
			if (firstItem == null) {
				firstItem = p.getPL_ID();
			}
			plansBox.addItem(p.getPL_ID());
			plansBox.setItemCaption(p.getPL_ID(), "[" + p.getPL_ID() + "]" + p.getPL_NAME());
		}
		if (firstItem != null) {
			plansBox.select(firstItem);
		}
	}

	private List makeListBySearch() {
		VOLmsExample example = new VOLmsExample();
		Criteria crit = example.createCriteria();

		String varify = (String) varifyBox.getValue();
		if ("手机号已经校检过".equals(varify)) {
			crit.andLMS_FLAG_VARIFYEqualTo("Y");
		} else if ("手机号未校检过".equals(varify)) {
			crit.andLMS_FLAG_VARIFYEqualTo("N");
		}
		crit.andLMS_MOBILEIsNotNull();// 手机号不能为空！

		crit.andLMS_DATEGreaterThanOrEqualTo(String.valueOf(startDate.getValue())).andLMS_DATELessThanOrEqualTo(
				String.valueOf(endDate.getValue()));

		String status = (String) statusBox.getValue();
		if ("仅显示发送失败记录".equals(status)) {
			crit.andLMS_SEND_FLAGEqualTo("N");
		} else if ("仅显示发送成功记录".equals(status)) {
			crit.andLMS_SEND_FLAGEqualTo("Y");
		}
		String from = (String)isComeFromMiniBox.getValue();
		if ("只显示来自迷你版".equals(from)) {
			crit.andLMS_FREEFLAG4EqualTo("Y");
		} else if ("只显示来自普通版".equals(from)) {
			crit.andLMS_FREEFLAG4IsNull();
		}
		
		if ("仅显示发送失败记录".equals(status)) {
			crit.andLMS_SEND_FLAGEqualTo("N");
		} else if ("仅显示发送成功记录".equals(status)) {
			crit.andLMS_SEND_FLAGEqualTo("Y");
		}

		if (checkCallMe.booleanValue()) {
			crit.andLMS_FREEFLAG3EqualTo("Y");
		}

		String refStr = (String) refCodeField.getValue();
		if (Tools.hasText(refStr)) {
			crit.andLMS_SEND_REFEqualTo(refStr);
		}
		String name = (String) nameField.getValue();
		if (Tools.hasText(name)) {
			crit.andLMS_LX_NAMELike(name + "%");
		}

		String mobile = (String) mobileField.getValue();
		if (Tools.hasText(mobile)) {
			crit.andLMS_MOBILELike(mobile + "%");
		}

		List list = getLmsDAO().selectByExample(example);
		return list;
	}

	void load() {
		list = makeListBySearch();
		int size = list == null ? 0 : list.size();
		if (size == 0) {
			app.getMainWindow().showNotification("没有记录");
		} else {
			app.getMainWindow().showNotification("查询记录条数:" + size);
		}

		if (LmsContainer == null) {
			try {
				LmsContainer = new LmsContainer();
			} catch (Throwable e) {
				logger.error(e);
				throw new RuntimeException(e);
			}
		}

		LmsContainer.removeAllItems();
		LmsContainer.addAll(list);

		LmsList.setContainerDataSource(LmsContainer);

		LmsList.setVisibleColumns(LmsContainer.NATURAL_COL_ORDER);
		LmsList.setColumnHeaders(LmsContainer.COL_HEADERS_SHOW);

		LmsForm.setItemDataSource(null);
	}

	private void buildMainLayout() {
		setSizeFull();
		vert = new VerticalSplitPanel();
		vert.setSizeFull();
		vert.setSplitPosition(100, Sizeable.UNITS_PIXELS);
		addComponent(vert);

		// add a label to the upper area
		topLayout = new VerticalLayout();
		topLayout.setSpacing(true);
		topLayout.setMargin(true);
		newButton = new Button("手动发送", new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {
				final Set<?> value = (Set<?>) LmsList.getValue();
				if (null == value || value.size() == 0) {
					getApplication().getMainWindow().showNotification("未选择记录", Notification.TYPE_WARNING_MESSAGE);
					return;
				}

				final int size = value.size();
				ConfirmDialog.confirmYesNo(getApplication(), "您将要手动发送" + size + "条记录，确定吗?", new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						StringBuffer logBuffer = new StringBuffer();
						int sucCount = 0;
						int falCount = 0;
						for (Iterator iterator = value.iterator(); iterator.hasNext();) {
							Object itemId = iterator.next();
							BeanItem item = (BeanItem) LmsList.getItem(itemId);
							VOLms bean = (VOLms) item.getBean();
							logger.debug("开始手动发送:" + bean.getLMS_GUID());
							boolean shouldCheckMobile = checkMobile.booleanValue();
							ServiceResult serviceResult = defaultService.sentLms(bean, shouldCheckMobile);
							if ("00".equals(serviceResult.getCode())) {
								sucCount++;
							} else {
								falCount++;
							}
							logBuffer.append(Tools.getDateTime() + ":" + serviceResult.toString() + "<br />");
						}
						app.getMainWindow().showNotification("发送完成! 发送成功条数:" + sucCount + "/" + size, Notification.TYPE_TRAY_NOTIFICATION);
						logContent.setValue(logBuffer.toString());
						load();
					}
				});

			}
		});
		newButton.setIcon(new ThemeResource("icons/clock.png"));

		xmlButton = new Button("查看XML报文", new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {
				final Set<?> value = (Set<?>) LmsList.getValue();
				if (null == value || value.size() == 0) {
					getApplication().getMainWindow().showNotification("未选择记录", Notification.TYPE_WARNING_MESSAGE);
					return;
				}

				if (value.size() > 1) {
					getApplication().getMainWindow().showNotification("请选择单条记录", Notification.TYPE_WARNING_MESSAGE);
					return;
				}

				final int size = value.size();

				for (Iterator iterator = value.iterator(); iterator.hasNext();) {
					Object itemId = iterator.next();
					BeanItem item = (BeanItem) LmsList.getItem(itemId);
					VOLms bean = (VOLms) item.getBean();
					// ServiceResult serviceResult =
					// defaultService.sentLms(bean, shouldCheckMobile);
					String xmlString = "";
					try {
						xmlString = defaultService.makeLmsTmplate(bean);
					} catch (Exception e) {
						logger.error(this, e);
						xmlString = "出错了:" + e;
					}
					AlertDialog.confirmYesNo(app, xmlString, null);
				}

			}
		});
		
		logButton = new Button("查看定时重发日志", new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {
				
				String logString = MemoryLog.fetchLogs();
				AlertDialog.confirmYesNo(app, logString , null);
				
			}
		});

		// topLayout.addComponent(newButton);
		// topLayout.addComponent(plansBox);
		HorizontalLayout topLayoutSub = new HorizontalLayout();
		HorizontalLayout topLayoutSub2 = new HorizontalLayout();
		topLayoutSub.setSizeUndefined();
		topLayoutSub.setMargin(false);
		topLayoutSub.setSpacing(true);
		topLayoutSub2.setSizeUndefined();
		topLayoutSub2.setMargin(false);
		topLayoutSub2.setSpacing(true);
		topLayoutSub.addComponent(new Label("起始日期:"));
		topLayoutSub.addComponent(startDate);
		topLayoutSub.addComponent(new Label("结束日期:"));
		topLayoutSub.addComponent(endDate);
		topLayoutSub.addComponent(statusBox);
		topLayoutSub.addComponent(new Label("状态码:"));
		topLayoutSub.addComponent(refCodeField);
		topLayoutSub.addComponent(new Label("姓名:"));
		topLayoutSub.addComponent(nameField);
		topLayoutSub.addComponent(new Label("手机号:"));
		topLayoutSub.addComponent(mobileField);
		topLayoutSub.addComponent(varifyBox);
		topLayoutSub.addComponent(checkCallMe);

		okButton = new Button("查找记录", new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {
				load();
			}
		});

		okButton.setIcon(new ThemeResource("icons/search.png"));
		topLayoutSub2.addComponent(isComeFromMiniBox);
		topLayoutSub2.addComponent(okButton);
		topLayoutSub2.addComponent(downloadReportLink);
		topLayoutSub2.addComponent(checkMobile);
		topLayoutSub2.addComponent(newButton);
		topLayoutSub2.addComponent(xmlButton);
		topLayoutSub2.addComponent(logButton);

		logContent.setWidth("500px");
		logPopup.setHideOnMouseOut(false);
		topLayoutSub2.addComponent(logPopup);

		topLayout.addComponent(topLayoutSub);
		topLayout.addComponent(topLayoutSub2);
		vert.setFirstComponent(topLayout);

		horiz = new HorizontalSplitPanel();
		horiz.setSplitPosition(66); // percent
		vert.setSecondComponent(horiz);

		// left component:
		LmsList = new LmsList(app, this);
		horiz.setFirstComponent(LmsList);

		rightLayout = new VerticalLayout();
		rightLayout.setSizeUndefined();
		rightLayout.setWidth("100%");
		rightLayout.setMargin(true);
		LmsForm = new LmsForm(this);

		rightLayout.addComponent(LmsForm);
		// right component:
		horiz.setSecondComponent(rightLayout);

	}

	public void valueChange(ValueChangeEvent event) {
		if (LmsList.isMultiSelect()) {
			Set<?> value = (Set<?>) event.getProperty().getValue();
			if (null == value || value.size() == 0) {
				return;
			} else {
				Item item = LmsList.getItem(value.iterator().next());
				LmsForm.setItemDataSource(item);
			}
		} else {
			Item item = LmsList.getItem(LmsList.getValue());
			LmsForm.setItemDataSource(item);
		}
	}

	public VOLmsDAO getLmsDAO() {
		return LmsDAO;
	}

	public void setLmsDAO(VOLmsDAO LmsDAO) {
		this.LmsDAO = LmsDAO;
	}

	public List fetchReportList() {
		return makeListBySearch();
	}

}
